package com.artup.controller;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.artup.common.ResponseResult;
import com.artup.service.WeChatService;

/**
 * 微信
 * @author hapday
 * @date 2017年7月24日 @Time 下午6:46:52
 */
@RestController
@RequestMapping( value = { "wechat" } )
public class WeChatController {
	private static final Logger LOGGER = LoggerFactory.getLogger(WeChatController.class);
	private static Map<String, String> payResultMap = new HashMap<String, String>();
	
	@Autowired
	private WeChatService weChatService;
	
	/**
	 * 创建【微信支付】之【统一下单】
	 * @param orderCode 订单号
	 * @param totalFee 总费用（单位：分）
	 * @return
	 */
	@RequestMapping( value = { "createWeChatMobilePayOrder" } )
	public ResponseResult createWeChatMobilePayOrder(String orderCode, float totalFee) {
		LOGGER.info("orderCode = {}, totalFee = {}", orderCode, totalFee);
		
		ResponseResult responseResult = this.weChatService.createWeChatMobilePayOrder(orderCode, totalFee);
		
		return responseResult;
	}
	
	/**
	 * 解析 XML
	 * @param request
	 * @return
	 * @throws Exception
	 * 2016年4月19日 上午10:09:58
	 */
	@SuppressWarnings("unchecked")
	private Map<String, Object> parseXml(HttpServletRequest request)
			throws Exception {
		// 解析结果存储在HashMap
		InputStream inputStream = request.getInputStream();
		// 读取输入流
		SAXReader reader = new SAXReader();
		
		Document document = null;
		
		if(null != inputStream){
			document = reader.read(inputStream);
		}
		// 得到xml根元素
		Element root = null;
		if(null != document){
			root = document.getRootElement();
		}
		
		// 得到根元素的所有子节点
		List<Element> elementList = null;
		if(null != root){
			elementList = root.elements();
		}

		Map<String, Object> payNoticeMap = new HashMap<String, Object>();
		// 遍历所有子节点
		for (Element element : elementList){
			payNoticeMap.put(element.getName(), element.getText());
		}
		
		LOGGER.info("微信支付结果 = " + JSONObject.toJSONString(payNoticeMap));

		// 释放资源
		inputStream.close();
		inputStream = null;

		return payNoticeMap;
	}

	/**
	 * 微信 APP 支付后的回调接口
	 * @param request
	 * @return
	 */
	@RequestMapping( value = { "weChatMobilePayCallback"}, method = { RequestMethod.GET, RequestMethod.POST } )
	public @ResponseBody String weChatMobilePayCallback(HttpServletRequest request) {
		String result = null;	// 返回结果集
		Map<String, Object> payNoticeMap = null;
		try {
			payNoticeMap = this.parseXml(request);
		} catch (Exception e) {
			LOGGER.error("解析[微信支付二次验证]的 XML 通知失败！异常：", e);
			
			result = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[支付失败]]></return_msg></xml>";

			return result;
		}
		
		LOGGER.info("payNoticeMap = " + JSONObject.toJSONString(payNoticeMap));
		String out_trade_no = (String) payNoticeMap.get("out_trade_no");
		
		ResponseResult responseResult = this.weChatService.weChatMobilePayCallback(payNoticeMap);
		payResultMap.put(out_trade_no, "uncompleted");
		
		
		if(1 == responseResult.getStatus()){
			result = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[支付成功]]></return_msg></xml>";
			
			payResultMap.put(out_trade_no, "success");
		} else {
			result = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[支付失败]]></return_msg></xml>";

			payResultMap.put(out_trade_no, "failure");
		}
		
		return result;
	}
	
	/**
	 * 查询【微信移动支付订单】
	 * @param orderCode 订单号
	 * @param weChatOrderCode 微信订单号
	 * @return
	 */
	@RequestMapping( value = { "queryWeChatMobilePayOrder" }, method = { RequestMethod.GET } )
	public ResponseResult queryWeChatMobilePayOrder(String orderCode, String weChatOrderCode) {
		LOGGER.info("orderCode = {}, weChatOrderCode = {}", orderCode, weChatOrderCode);
		
		ResponseResult responseResult = this.weChatService.queryWeChatMobilePayOrder(orderCode, weChatOrderCode);
		
		return responseResult;
	}
}
